<template>
  <div id="articleEditor">
    <el-button type="primary" style="margin-bottom:10px" icon="el-icon-back" size="mini" @click="$router.push('/articleList')">返回</el-button>
    <el-button type="primary" style="margin-bottom:10px" size="mini" @click="submit">发表文章</el-button>
    <mavon-editor
      id="md"
      ref="md"
      v-model="content"
      style="min-height: 600px"
      @imgAdd="$imgAdd"
      @change="change"
    />
  </div>
</template>

<script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { getArticleId, articleAdd, articleEdit } from '@/api/article'
import { getCategory } from '@/api/category'
export default {
  // 注册
  components: {
    mavonEditor
  },
  data() {
    return {
      content: '', // 输入的markdown
      html: '', // 及时转的html
      ruleForm: {},
      id: null
    }
  },
  created() {
    const { id } = this.$route.query
    this.id = id
    if (id) {
      this.query(id)
    } else {
      this.ruleForm = this.$route.query
    }
    this.getCategory()
  },
  methods: {
    query(id) {
      getArticleId(id).then((res) => {
        this.ruleForm = res[0]
        this.content = res[0].content
      })
    },
    // 获取分类
    getCategory() {
      getCategory().then((res) => {
        this.category = res
      })
    },
    // 绑定@imgAdd event
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      formdata.append('image', $file)
    },
    // 所有操作都会被解析重新渲染
    change(value, render) {
      // render 为 markdown 解析后的结果[html]
      this.ruleForm.content = render
    },
    // 提交
    submit() {
      // 将分类标签填入
      this.category.forEach((e) => {
        if (e.id === this.ruleForm.category_id) {
          this.ruleForm.category_name = e.name
          return
        }
      })
      const http = this.id ? articleEdit : articleAdd
      http(this.ruleForm).then((res) => {
        this.$message.success('文章编辑成功')
        this.$router.push('/articleList')
        this.ruleForm = {}
      })
    }
  }
}
</script>
<style scoped lang="less">
#articleEditor {
  overflow: auto;
  margin: 10px;
  // height: calc(100vh - 150px);
  #md {
    height: 100%;
  }
}
</style>
